<template>
  <div id="app">
    <mu-appbar id="appbar" style="width: 100%;">
      <label title="基于Gitee的Chrome书签同步工具" class="title" slot="left">Chrome书签同步工具</label>

      <div style="padding-right: 20px;" slot="right">
        <mu-tooltip content="开启/关闭书签自动同步服务">
          <span>
            <mu-switch v-model="open" slot="right" @click="openSyncService"></mu-switch>
          </span>
        </mu-tooltip>
      </div>

    </mu-appbar>

    <div class="paper">
      <mu-form ref="config-form" :model="form" label-position="top">
        <mu-form-item label="书签存放路径" prop="localBookmarkPath" :rules="rules.localBookmarkPathRules" class="text-align-left">
          <mu-text-field v-model="form.localBookmarkPath" @change="saveConfig"></mu-text-field>
        </mu-form-item>
        <mu-form-item label="用户授权码" prop="accessToken" :rules="rules.accessTokenRules" class="text-align-left">
          <mu-text-field v-model="form.accessToken" :action-icon="visibility ? 'visibility_off' : 'visibility'" :action-click="() => (visibility = !visibility)" :type="visibility ? 'text' : 'password'" @change="saveConfig"></mu-text-field>
        </mu-form-item>
        <mu-form-item label="仓库拥有者" prop="owner" :rules="rules.ownerRules" class="text-align-left">
          <mu-text-field v-model="form.owner" @change="saveConfig"></mu-text-field>
        </mu-form-item>
        <mu-form-item label="仓库名称" prop="repository" :rules="rules.repositoryRules" class="text-align-left">
          <mu-text-field v-model="form.repository" @change="saveConfig"></mu-text-field>
        </mu-form-item>
        <mu-form-item label="仓库中书签文件路径" prop="path" :rules="rules.pathRules" class="text-align-left">
          <mu-text-field v-model="form.path" @change="saveConfig"></mu-text-field>
        </mu-form-item>
      </mu-form>
    </div>

    <decision-maker ref="decision-maker"></decision-maker>

    <mu-tooltip content="立即同步">
      <mu-button class="sync-btn" fab @click="syncBookmark">
        <mu-icon value="sync"></mu-icon>
      </mu-button>
    </mu-tooltip>

  </div>
</template>

<script>

import DecisionMaker from "./component/DecisionMaker";
import 'material-design-icons/iconfont/material-icons.css';
import plugin_api from './plugin/plugin-api';

let timer = undefined;

export default {
  name: 'App',
  components: {
    DecisionMaker
  },

  data(){
    return {
      open: false,
      visibility: false,
      rules: {
        localBookmarkPathRules: [
          { validate: (val) => !!val, message: '必须填写书签存放路径'}
        ],
        accessTokenRules: [
          { validate: (val) => !!val, message: '必须填写用户授权码'}
        ],
        ownerRules: [
          { validate: (val) => !!val, message: '必须填写仓库拥有者'}
        ],
        repositoryRules: [
          { validate: (val) => !!val, message: '必须填写仓库名称'}
        ],
        pathRules: [
          { validate: (val) => !!val, message: '必须填写仓库中书签文件路径'}
        ]
      },
      form: {
        localBookmarkPath: '',
        accessToken: '',
        owner: '',
        repository: '',
        path: ''
      },

    }
  },

  mounted() {
    this.loadConfig();
  },

  methods: {
    loadConfig(){
      if(plugin_api.pluginStatus.isReady){
        this.form.localBookmarkPath = plugin_api.config.get(plugin_api.Keys.LOCAL_BOOKMARK_PATH);
        this.form.accessToken = plugin_api.config.get(plugin_api.Keys.REMOTE_GITEE_ACCESS_TOKEN);
        this.form.owner = plugin_api.config.get(plugin_api.Keys.REMOTE_GITEE_OWNER);
        this.form.repository = plugin_api.config.get(plugin_api.Keys.REMOTE_GITEE_REPOSITORY_NAME);
        this.form.path = plugin_api.config.get(plugin_api.Keys.REMOTE_GITEE_BOOKMARK_PATH);
      }else {
        setTimeout(()=>{
          this.loadConfig();
        }, 1000);
      }

    },
    saveConfig(){
      plugin_api.config.set(plugin_api.Keys.LOCAL_BOOKMARK_PATH,       this.form.localBookmarkPath);
      plugin_api.config.set(plugin_api.Keys.REMOTE_GITEE_ACCESS_TOKEN, this.form.accessToken);
      plugin_api.config.set(plugin_api.Keys.REMOTE_GITEE_OWNER,        this.form.owner);
      plugin_api.config.set(plugin_api.Keys.REMOTE_GITEE_REPOSITORY_NAME, this.form.repository);
      plugin_api.config.set(plugin_api.Keys.REMOTE_GITEE_BOOKMARK_PATH,   this.form.path);
    },

    openSyncService(){
      if(this.open){
        this.syncBookmark();
        if(!timer){
          timer = setInterval(()=>{
            this.syncBookmark();
          }, 1000*60); // 1分钟同步一次
        }
      }else {
        if(timer){
          clearInterval(timer);
          timer = undefined;
        }
      }
    },

    syncBookmark(){
      const self = this;

      this.$refs['config-form'].validate().then(pass => {
        if(pass){
          const decisionMaker = self.$refs['decision-maker'];
          const localBookmarkPath = plugin_api.config.get(plugin_api.Keys.LOCAL_BOOKMARK_PATH);
          const firstRunRecorder = new plugin_api.FirstRunRecorderImpl(localBookmarkPath);
          const bookmarkManager = new plugin_api.BookmarkManager(plugin_api.config,  decisionMaker, firstRunRecorder);

          bookmarkManager.syncBookmark().then((result)=>{
            self.$toast.message(result);
          }).catch(e => {
            if(e === undefined){
              self.$toast.error('同步失败，发生了未知错误')
              return;
            }
            else if(e instanceof Error){
              self.$toast.error(e.message);
              return;
            }
            else {
              self.$toast.error(JSON.stringify(e));
              return;
            }
          });
        }
      });
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

.title{
  font-size: 16px;
  padding-left: 14px;
}

#appbar {
  position:absolute;
  z-index: 100;
}

.paper{
  padding-top: 80px;
  padding-left: 24px;
  padding-right: 24px;
  z-index: 90;
}
.text-align-left {
  text-align: left;
}

.sync-btn {
  position: fixed !important;
  right: 20px;
  top: 420px;
}

</style>
